G2G = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceEvent-2.0", "AceDB-2.0", "AceDebug-2.0", "FuBarPlugin-2.0")

G2G:RegisterDB("G2GSV", "G2GSVPC")
G2G:RegisterDefaults("profile", {
	["channel"] = "",
} )
local vars = {
	["version"] = GetAddOnMetadata("G2G", "Version"),
	["channel"] = "",
	["cID"] = nil,
	["playername"] = nil,
	["currentactive"] = nil,
}

G2G.hasIcon = "Interface\\Icons\\INV_Scroll_02"
function G2G:OnInitialize()
	self:UpdateVars(self.db.profile.channel)
	
	self.OnMenuRequest = {
		type="group",
		args = {
			channel = {
				name = "Channel", type = 'text',
				desc = "Set the sync channel to use",
				usage = "<channel name>",
				get = 	function()
							return self.db.profile.channel
						end,
				set = 	function(v)
							self:UpdateVars(v)
						end,
			},
		},
	}
	
	G2G:RegisterChatCommand({"/g2g"}, self.OnMenuRequest)

end

function G2G:OnEnable()
	self:SetDebugging(true)
    self:RegisterEvent("CHAT_MSG_CHANNEL")
    self:RegisterEvent("CHAT_MSG_GUILD")
    self:RegisterEvent("CHAT_MSG_ADDON")
    self:RegisterEvent("CHAT_MSG_OFFICER")
    self:RegisterEvent("CHAT_MSG_CHANNEL_LEAVE")
	self:Debug("G2G version", vars.version, "loaded");
	
	vars.playername = UnitName("player")
	vars.currentactive = vars.playername
	
	self:Ping("NU")
	self:Ping("VC")
end

function G2G:OnDisable()
	
end

function G2G:CHAT_MSG_ADDON(...)
--Redirects everything to the system command with the args (Message, sender)
	if not (arg1 == "G2G") then return end
	self:Debug("Debug", arg2, arg4)
	self:System(arg2, arg4)
end

function G2G:CHAT_MSG_CHANNEL_LEAVE(...)
	if not(arg9 == vars.channel) then return end 				--Wrong channel
	self:Debug(arg2, "is leaving")
	if (vars.currentactive == arg2) then
		self:Debug(arg2, "was the active, time to find another")
		vars.currentactive = vars.playername
		self:Ping("ME")
	end
end

function G2G:CHAT_MSG_GUILD(...)
	if not(self:ImActive()) then return end
	if string.find(arg1,"%[.*%]:.*") then return end --Prevent an endless loop
	SendChatMessage("G:" .. arg2 .. ":" ..self:ChatLink(arg1), "CHANNEL", nil, vars.cID)
end

function G2G:CHAT_MSG_OFFICER(...)
	if not(self:ImActive()) then return end
	if string.find(arg1,"%[.*%]:.*") then return end --Prevent an endless loop
	SendChatMessage("O:" .. arg2 .. ":" ..self:ChatLink(arg1), "CHANNEL", nil, vars.cID)
end

function G2G:CHAT_MSG_CHANNEL(...)
	if not(arg9 == vars.channel) then return end 					--Wrong channel
	if not(self:ImActive()) then return end							--not active, don't care
	if(arg2 == vars.playername) then return end 					--I sent it, ignore the message	
	
	vars.cID = arg8
	local s1 = string.find(arg1, ":", 3)		--Finds the : seperating the sender and the message
	local sender = string.sub(arg1, 3, s1-1)	--Grabs the text between the :'s, getting the sender
	self:Debug(arg2)

	local c = string.sub(arg1, 1, 1)			--Gets the type of message so we know where to send it
	if (c == "G") then 
		c = "GUILD"
	else
		c = "OFFICER"
	end
	SendChatMessage("["..sender.."]: "..self:ChatLink(string.sub(arg1, s1+1)), c)
end


function G2G:UpdateVars(chan)
	if not(chan == nil) then
		self.db.profile.channel = chan
		vars.channel = chan
		vars.cID = GetChannelName(chan)
	end
end

function G2G:Bug()
	for k, v in pairs(vars.list) do
		self:Print(k, v)
	end
end

function G2G:ImActive()
	return vars.currentactive == vars.playername
end

function G2G:Ping(t)
--[[
Types:
	NU: I'm a new user.  Letting everyone know I'm here
	IA: I'm the current active.  Used when a new user joins the channel by the active
	ME: My name.  Used when a new active is needed.  Checked against own name for alphabetical order
	VC: Version check.  Spams anyone with an out of date version
]]--
	SendAddonMessage("G2G", t, "GUILD")
end

function G2G:System(cmd, user)
	if (cmd == "IA") then
		vars.currentactive = user
	elseif (cmd == "NU") then 
		if (self:ImActive()) and not(user == vars.playername) then self:Ping("IA") end
	elseif (cmd == "ME") then
		if (user < vars.currentactive) then vars.currentactive = user end
	elseif string.find(cmd, "VC") then
		local v = string.sub(cmd, 4)
		self:Debug(v, vars.version)
		if (vars.version < v) then self:Print("You have an out of date version.  Please update.")
		elseif (vars.version > v) then self:Ping("VC:" .. vars.version)	end
	end
end

function G2G:ChatLink(text)
	if string.find(text, "|Hitem:")	then
		--compose
		return string.gsub(text,"|c(%x+)|Hitem:(%d-):(%d-):(%d-):(%d-)|h%[([^%]]-)%]|h|r", "{CLINK:%1:%2:%3:%4:%5:%6}")
	else
		-- decompose
		return string.gsub(text,"{CLINK:(%x+):(%d-):(%d-):(%d-):(%d-):([^}]-)}","|c%1|Hitem:%2:%3:%4:%5|h[%6]|h|r")
	end
end
